package com.example.swim.Config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LiYa
 * @create 2022-12-02 10:17
 */
@Configuration
public class DruidConfig {

//    绑定yml文件中druid配置的数据源
    @ConfigurationProperties(prefix="spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        return new DruidDataSource();
    }


//    后台监控 相当于web.xml   ServletRegistrationBean
//    因为SpringBoot 内置了servlet容器，所以没有web.xml, 替代方法： ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

        HashMap<String, String> initParameters=new HashMap<>();
//        后台需要有人登录，初始化参数，死的
        initParameters.put("loginUsername","liya");//登录key是固定的loginUsername，loginPassword。
        initParameters.put("loginPassword","123");


//        允许谁可以访问
        initParameters.put("allow","");

//         禁止谁能访问
//        initParameters.put("liya", "192.168.11.123");


//        设置初始化参数
        bean.setInitParameters(initParameters);
        return bean;
    }


//    filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

//        可以过滤哪些请求呢？
        Map<String, String> initParameters=new HashMap<>();

//        这些东西不进行统计
        initParameters.put("exclusions","*.js,*.css,/druid/*");

        bean.setInitParameters(initParameters);

        return bean;

    }
}
